const express = require('express');
const path=require('path');
const router = express.Router(); // 路由器
const lunboModel=require('../models/lunbo');



//定义后台的访问url地址
router.get('/index',(req,res)=>{
//    art-template配置
    if (req.cookies['isLogin'] != 1) {
        // 用户未登录
        res.redirect('/admin/login');
    } else {
        res.render('index', { username: req.cookies['username'] });
    }
    // res.render('index')
})

router.get('/welcome',(req,res)=>{
//    art-template配置
    res.render('welcome')
})



//产品中心后天访问url地址





/*完成上传功能*/
const multer = require('multer');
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../public/uploads/'))
    },
    filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        /*path.extname( file.originalname ) 可以获取到文件的扩展名 1.jpg==> .jpg*/
        cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
    }
})
const upload = multer({storage: storage})

router.post('/lunboStore',upload.fields([{name: 'lunbo'}]),(req,res)=>{
    let picPaths = {lunbo: ''};

    if (req.files) {
        for (let attr in req.files) {
            picPaths[attr] = req.files[attr][0].filename;
        }
    }
    console.log(picPaths);
    console.log(picPaths.pic);
    if(picPaths!=null){
        let  lunboModelObj= new lunboModel({
            pic: picPaths.lunbo,
        });

        lunboModelObj.save((error, data) => {
            if (error) {
                console.log(error);
                res.redirect('/admin/lunbotu-show');
            } else {
                console.log(data);
                res.redirect('/admin/lunbotu-show');

            }
        });
    }else{

        res.render('/admin/lunbotu-show');
    }

})
router.get('/lunbotu-show', async (req, res) => {

    const info = await lunboModel.find();
    // console.log(info);
    if (info) {


        res.render('lunbotu-show', {info}); // {}

    } else {
        /* 如果不存在，应该是做信息的添加操作 */
        res.render('lunbotu-show', {info: {}});
    }

});
router.get('/lunbotu-delete/:id', async (req, res) => {

    console.log(req.params);
    // res.json(req.params); // res.json() 可以把一个js对象转换为一个对象格式的字符串，方便查看，res.json会把格式化字符串的对象响应给浏览器
    let cateId = req.params.id;

    try {
        await lunboModel.deleteOne({_id: cateId});

        res.redirect('back'); // back 代表的是当前的页面的上一级页面。指的是这个的来源路径

    } catch (e) {
        res.redirect('back');

    }


});


module.exports = router;